package cn.itcast.goods.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.StatusConstant;
import cn.itcast.exception.CustomException;
import cn.itcast.goods.dto.CategoryDTO;
import cn.itcast.goods.dto.CategoryPageQueryDTO;
import cn.itcast.goods.mapper.CategoryMapper;
import cn.itcast.goods.mapper.DishMapper;
import cn.itcast.goods.mapper.SetmealMapper;
import cn.itcast.goods.pojo.Category;
import cn.itcast.goods.service.CategoryService;
import cn.itcast.result.PageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增分类
     *
     * @param categoryDTO
     */
    @CacheEvict(cacheNames = "category:list", allEntries = true)
    @Override
    public void save(CategoryDTO categoryDTO) {

        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);

        // 默认为禁用状态
        category.setStatus(StatusConstant.DISABLE);

        categoryMapper.insert(category);
    }

    /**
     * 分类分页查询
     *
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageBean pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());

        Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO);

        return new PageBean(page.getTotal(), page.getResult());
    }

    /**
     * 删除分类
     *
     * @param id
     */
    @CacheEvict(cacheNames = "category:list", allEntries = true)
    @Override
    public void deleteById(Long id) {

        if (dishMapper.getByCategoryId(id).size() != 0) {
            throw new CustomException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        if (setmealMapper.getByCategoryId(id).size() != 0) {
            throw new CustomException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }


        categoryMapper.deleteById(id);
    }

    /**
     * 修改分类信息
     *
     * @param categoryDTO
     */
    @CacheEvict(cacheNames = "category:list", allEntries = true)
    @Override
    public void update(CategoryDTO categoryDTO) {

        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);


        categoryMapper.update(category);
    }

    /**
     * 启用禁用分类
     *
     * @param status
     * @param id
     */
    @CacheEvict(cacheNames = "category:list", allEntries = true)
    @Override
    public void startOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                .build();
        categoryMapper.update(category);
    }

    /**
     * 根据类型查询分类
     *
     * @param type
     * @return
     */
    @Cacheable(cacheNames = "category:list", key = "#type == null ? 'null' : #type")
    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.getByType(type);
    }

    /**
     * 根据id查询分类
     *
     * @param id
     * @return
     */
    @Override
    public Category getById(Long id) {
        return categoryMapper.getById(id);
    }

    /**
     * 将菜品信息导出为Excel报表
     *
     * @param response
     */
    @SneakyThrows
    @Override
    public void exportCategory(HttpServletResponse response) {
        List<Category> list = categoryMapper.pageQuery(new CategoryPageQueryDTO());

        InputStream is = this.getClass().getClassLoader().getResourceAsStream("templates/category分类.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(is);
        XSSFSheet sheet = excel.getSheetAt(0);

        for (int i = 0; i < list.size(); i++) {
            Category category = list.get(i);
            XSSFRow row = sheet.getRow(i + 1);
            if (row == null) row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(category.getId());
            row.createCell(1).setCellValue(category.getType());
            row.createCell(2).setCellValue(category.getName());
            row.createCell(3).setCellValue(category.getSort());
            row.createCell(4).setCellValue(category.getStatus());
            row.createCell(5).setCellValue(category.getCreateTime().toString());
            row.createCell(6).setCellValue(category.getUpdateTime().toString());
            row.createCell(7).setCellValue(category.getCreateUser());
            row.createCell(8).setCellValue(category.getUpdateUser());
        }

        ServletOutputStream os = response.getOutputStream();
        excel.write(os);

        os.flush();
        os.close();
        excel.close();

    }

}
